package com.gaoyuzhe.controller;

import com.gaoyuzhe.service.PaymentService;
import com.gaoyuzhe.to.ReturnValue;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author gaoyuzhe
 */
@RestController
@RequestMapping("/payment/hystrix")
@Slf4j
public class PaymentController {
    @Autowired
    private PaymentService paymentService;

    /**
     * 正常测试案例
     *
     * @param id id
     * @return 结果
     */
    @RequestMapping("/paymentOk/{id}")
    public String paymentOk(@PathVariable Integer id) {
        String paymentOk = paymentService.paymentOk(id);
        log.info(paymentOk);
        return paymentOk;
    }

    /**
     * 超时测试案例
     *
     * @param id id
     * @return 结果
     */
    @RequestMapping("/paymentTimeout/{id}")
    public String paymentTimeout(@PathVariable Integer id) {
        String paymentTimeout = paymentService.paymentTimeout(id);
        log.info(paymentTimeout);
        return paymentTimeout;
    }

    @HystrixCommand(fallbackMethod = "circuitFallback",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),
    })
    @RequestMapping("/circuit/{id}")
    public String circuit(@PathVariable("id") Integer id) {
        int number = 2;
        if(id % number ==0){
            throw new RuntimeException("你被"+number+"整除了，傻瓜");
        }
        return "成功访问";
    }

    public String circuitFallback(Integer id){
        return "circuitFallback 我替你管了";
    }
}
